﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Routing;

using MvcEngine.Core;
using MvcEngine.Core.Repositories;
using System.IO;
using MvcEngine.Core.Helpers;
using MvcEngine.Core.Extensions;
using MvcEngine.Core.Configuration;
using System.Drawing;
using MvcEngine.Core.Utils;

namespace MvcEngine.Core.HttpHandlers
{
    public class CaptchaHandler : IHttpHandler
    {
        private const int HMargin = 5;
        private const int VMargin = 3;

        #region IHttpHandler Members
 
        public bool IsReusable
        {
            get { return false; }
        }

        public virtual void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "image/jpeg";
            string key = context.Request.QueryString[CaptchaConsts.KeyName];

            if (!string.IsNullOrEmpty(key)) 
            {
                var value = CacheManager.Current.GetFromCache(key) as string;
                if (value != null)
                {
                    List<Letter> letter = new List<Letter>();
                    int TotalWidth = 0;
                    int MaxHeight = 0;
                    foreach (char c in value)
                    {
                        var ltr = new Letter(c);
                        letter.Add(ltr);
                        int space = (new Random()).Next(5) + 1;
                        ltr.space = space;
                        System.Threading.Thread.Sleep(1);
                        TotalWidth += ltr.LetterSize.Width + space;
                        if (MaxHeight < ltr.LetterSize.Height)
                            MaxHeight = ltr.LetterSize.Height;
                        System.Threading.Thread.Sleep(1);
                    }

                    using (Bitmap bmp = new Bitmap(TotalWidth + HMargin, MaxHeight + VMargin))
                    {
                        using (var Grph = Graphics.FromImage(bmp))
                        {
                            Grph.FillRectangle(new SolidBrush(Color.Lavender), 0, 0, bmp.Width, bmp.Height);
                            Pixelate(bmp);

                            Grph.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                            Grph.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                            int xPos = HMargin;
                            foreach (var ltr in letter)
                            {
                                Grph.DrawString(ltr.letter.ToString(), ltr.font, new SolidBrush(Color.Navy), xPos, VMargin);
                                xPos += ltr.LetterSize.Width + ltr.space;
                            }

                            bmp.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
                        }
                    }
                }
                else 
                {
                    LogHelper.Current.WriteWarning("The captcha key from the query string is not correct. There is no such value in the cache.");
                }
            }
        }

        private void Pixelate(Bitmap bmp)
        {
            Color[] Colors = { Color.Gray, Color.Red, Color.Blue, Color.Olive };
            for (int i = 0; i < 200; i++)
            {
                var rnd = new Random(DateTime.Now.Millisecond);
                var grp = Graphics.FromImage(bmp);
#warning change hardcoded string
                using (Image background = Image.FromFile(HttpContext.Current.Server.MapPath("~/areas/startersite/content/images/captcha/captcha1.png")))
                {
                    grp.DrawImage(background, new Rectangle(0, 0, bmp.Width, bmp.Height));
                    grp.Dispose();
                }
            }
        }

        #endregion
    }

    public class Letter
    {
        string[] ValidFonts = { "Segoe Script", "Century", "Eccentric Std", "Freestyle Script", "Viner Hand ITC" };
        public Letter(char c)
        {
            Random rnd = new Random();
            font = new Font(ValidFonts[rnd.Next(ValidFonts.Count() - 1)], rnd.Next(20) + 20, GraphicsUnit.Pixel);
            letter = c;
        }
        public Font font
        {
            get;
            private set;
        }
        public Size LetterSize
        {
            get
            {
                var Bmp = new Bitmap(1, 1);
                var Grph = Graphics.FromImage(Bmp);
                return Grph.MeasureString(letter.ToString(), font).ToSize();
            }
        }
        public char letter
        {
            get;
            private set;
        }
        public int space
        {
            get;
            set;
        }

    }


}
